<?php

namespace app\jigou\controller\qingdongams\department;

use addons\qingdongams\model\Achievement as AchievementModel;
use addons\qingdongams\model\AchievementRecords;
use addons\qingdongams\model\ContractRatio;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\Flow;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Receivables;
use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\StaffDepartment;
use addons\qingdongams\model\Staff;
use think\DB;
use think\Exception;
use think\Session;

/**
 * 业绩目标
 */
class Achievement extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \addons\qingdongams\model\Achievement();
    }

    /**
     * 业绩目标列表
     * @return string|\think\response\Json
     */
    public function index()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $year = $filter['year'];
            $status = $filter['status'];
            $staff_id = $filter['staff_id'] ?? 0;
            $where = [];
            if ($staff_id) {
                $where['obj_id'] = $staff_id;
            }else{
                $where['obj_id']=['in',Staff::getMyStaffIds()];
            }

            $achievements=AchievementModel::where(['type'=>3,'year'=>$year,'status'=>$status])
                ->where($where)
                ->with(['staff'])
                ->select();
            $achievements=collection($achievements)->toArray();
            $ids=[];
            foreach ($achievements as $v){
                $ids[]=$v['obj_id'];
            }
            if($status == 1){//订单金额
                $contracts=ContractRatio::where([
                    'contract.check_status'=>2, 'contract_ratio.staff_id' => ['in',$ids],
                    'contract.order_date'=>['like', $year . '%']
                ])->with(['contract'])->select();
                $contracts=collection($contracts)->toArray();
                $contractData=[];
                foreach ($contracts as $v) {
                    $order_date = $v['contract']['order_date'];
                    $month = date('Y-m', strtotime($order_date));
                    $contractData[$v['staff_id']][$month]['money'][] = $v['ratio_money'];
                }

            }else{
                $receivables      = Receivables::where([
                    'owner_staff_id' => ['in',$ids],
                    'check_status'   => 2,
                    'return_time'     => ['like', $year . '%'],
                ])->select();
                $contracts=collection($receivables)->toArray();
                $contractData=[];
                foreach ($contracts as $v) {
                    $return_time = $v['return_time'];
                    $month = date('Y-m', strtotime($return_time));
                    $contractData[$v['owner_staff_id']][$month]['money'][] = $v['money'];
                }
            }

            $data=[];
            foreach ($contractData as $owner_staf_id=>$d){
                foreach ($d as $month=>$money){
                    $data[$owner_staf_id][$month]=array_sum($money['money']);
                }
            }
            foreach ($achievements as $k=>$v) {
                $v['january_money'] = $data[$v['obj_id']][$year . '-01'] ?? 0;
                $v['february_money'] = $data[$v['obj_id']][$year . '-02'] ?? 0;
                $v['march_money'] = $data[$v['obj_id']][$year . '-03'] ?? 0;
                $v['april_money'] = $data[$v['obj_id']][$year . '-04'] ?? 0;
                $v['may_money'] = $data[$v['obj_id']][$year . '-05'] ?? 0;
                $v['june_money'] = $data[$v['obj_id']][$year . '-06'] ?? 0;
                $v['july_money'] = $data[$v['obj_id']][$year . '-07'] ?? 0;
                $v['august_money'] = $data[$v['obj_id']][$year . '-08'] ?? 0;
                $v['september_money'] = $data[$v['obj_id']][$year . '-09'] ?? 0;
                $v['october_money'] = $data[$v['obj_id']][$year . '-10'] ?? 0;
                $v['november_money'] = $data[$v['obj_id']][$year . '-11'] ?? 0;
                $v['december_money'] = $data[$v['obj_id']][$year . '-12'] ?? 0;
                $v['year_money'] = $v['january_money'] + $v['february_money'] + $v['march_money'] + $v['april_money'] + $v['may_money'] + $v['june_money'] + $v['july_money'] + $v['august_money'] + $v['september_money'] + $v['october_money'] + $v['november_money'] + $v['december_money'];


                $v['january_ratio']= ($v['january_money'] && intval($v['january'])) ?
                    sprintf("%.2f", $v['january_money'] / $v['january'] * 100)  .'%': 0;
                $v['february_ratio']= ($v['february_money'] && intval($v['february'])) ?
                    sprintf("%.2f", $v['february_money'] / $v['february'] * 100)  .'%': 0;
                $v['march_ratio']= ($v['march_money'] && intval($v['march'])) ?
                    sprintf("%.2f", $v['march_money'] / $v['march'] * 100)  .'%': 0;
                $v['april_ratio']= ($v['april_money'] && intval($v['april'])) ?
                    sprintf("%.2f", $v['april_money'] / $v['april'] * 100) .'%' : 0;
                $v['may_ratio']= ($v['may_money'] && intval($v['may'])) ?
                    sprintf("%.2f", $v['may_money'] / $v['may'] * 100)  .'%': 0;
                $v['june_ratio']= ($v['june_money'] && intval($v['june'])) ?
                    sprintf("%.2f", $v['june_money'] / $v['june'] * 100)  .'%': 0;
                $v['july_ratio']= ($v['july_money'] && intval($v['july'])) ?
                    sprintf("%.2f", $v['july_money'] / $v['july'] * 100)  .'%': 0;

                $v['august_ratio']= ($v['august_money'] && intval($v['august'])) ?
                    sprintf("%.2f", $v['august_money'] / $v['august'] * 100) .'%' : 0;
                $v['september_ratio']= ($v['september_money'] && intval($v['september'])) ?
                    sprintf("%.2f", $v['september_money'] / $v['september'] * 100) .'%' : 0;
                $v['october_ratio']= ($v['october_money'] && intval($v['october'])) ?
                    sprintf("%.2f", $v['october_money'] / $v['october'] * 100)  .'%': 0;
                $v['november_ratio']= ($v['november_money'] && intval($v['november'])) ?
                    sprintf("%.2f", $v['november_money'] / $v['november'] * 100) .'%' : 0;
                $v['december_ratio']= ($v['december_money'] && intval($v['december'])) ?
                    sprintf("%.2f", $v['december_money'] / $v['december'] * 100)  .'%': 0;
                $v['year_ratio']= ($v['year_money'] && intval($v['yeartarget'])) ?
                    sprintf("%.2f", $v['year_money'] / $v['yeartarget'] * 100) .'%' : 0;

                $v['one']=sprintf("%.2f",($v['january'] + $v['february'] + $v['march']));
                $v['two']= sprintf("%.2f",($v['april'] + $v['may'] + $v['june']));
                $v['three']=sprintf("%.2f",($v['july'] + $v['august'] + $v['september']));
                $v['four']=sprintf("%.2f",($v['october'] + $v['november'] + $v['december']));

                $v['one_money']=$v['january_money'] + $v['february_money'] + $v['march_money'];
                $v['two_money']=$v['april_money'] + $v['may_money'] + $v['june_money'];
                $v['three_money']=$v['july_money'] + $v['august_money'] + $v['september_money'];
                $v['four_money']=$v['october_money'] + $v['november_money'] + $v['december_money'];

                $v['one_ratio']= ($v['one_money'] && $v['one']>0) ?
                    sprintf("%.2f", $v['one_money'] / $v['one'] * 100) .'%': 0;
                $v['two_ratio']= ($v['two_money'] && $v['two']>0) ?
                    sprintf("%.2f", $v['two_money'] / $v['two'] * 100)  .'%': 0;
                $v['three_ratio']= ($v['three_money'] && $v['three']>0) ?
                    sprintf("%.2f", $v['three_money'] / $v['three'] * 100) .'%' : 0;
                $v['four_ratio']= ($v['four_money'] && $v['four']>0) ?
                    sprintf("%.2f", $v['four_money'] / $v['four'] * 100)  .'%': 0;

                $achievements[$k]=$v;
            }
            $result = array("total" => count($achievements), "rows" => $achievements);

            return json($result);
        }

        $this->assign('department', StaffDepartment::getList());
        $staffs = Staff::where(['id'=>['in',Staff::getMyStaffIds()]])->field('id,name')->select();
        $this->assign('staffs', $staffs);
        $this->assign('years', getYears());

        return $this->view->fetch();
    }

    /**
     * 个人目标
     */
    public function personal()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $year = $filter['year'];
            $status = $filter['status'];

            $list = Staff::where(['id'=>$this->_staff->id])->with([
                "achievement" => function ($query) use ($year, $status) {
                    $query->where(['year' => $year, 'status' => $status]);
                }
            ])->paginate();
            $rows = $list->items();
            foreach ($rows as $v) {

                if (empty($v['achievement'])) {
                    $v['all'] = 0;
                    $v['one'] = 0;
                    $v['two'] = 0;
                    $v['three'] = 0;
                    $v['four'] = 0;
                } else {
                    $ach = $v['achievement'];
                    $v['all'] = round($ach['january'] + $ach['february'] + $ach['march'] + $ach['april'] + $ach['may'] + $ach['june'] + $ach['july'] + $ach['august'] + $ach['september'] + $ach['october'] + $ach['november'] + $ach['december'], 2);
                    //季度
                    $v['one'] = round($ach['january'] + $ach['february'] + $ach['march'], 2);
                    $v['two'] = round($ach['april'] + $ach['may'] + $ach['june'], 2);
                    $v['three'] = round($ach['july'] + $ach['august'] + $ach['september'], 2);
                    $v['four'] = round($ach['october'] + $ach['november'] + $ach['december'], 2);
                }
                $v['year'] = $year;
                $v['status'] = $status;
            }
            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }

        $this->assign('department', StaffDepartment::getList());
        $staffs = Staff::where(['id'=>['in',Staff::getMyStaffIds()]])->field('id,name')->select();
        $this->assign('staffs', $staffs);
        $this->assign('years', getYears());

        return $this->view->fetch();
    }

    /**
     * 业绩目标修改日志
     * @return string|\think\response\Json
     */
    public function records()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $staff_id=$this->_staff->id;
            $list= AchievementRecords::where(['owner_staff_id'=>$staff_id])->with(['staff'])->order('id desc')->paginate();
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 新建业绩目标
     * @param null $ids
     * @return string
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $params = $this->preExcludeFields($params);
            $staff_ids=$params['staff_ids'];
            unset($params['staff_ids']);
            $staff_ids=explode(',',$staff_ids);
            $data=[];
            $flow = Flow::getsteplist(Flow::ACHIEVEMENT_STATUS);
            foreach ($staff_ids as $sid) {
                $params['obj_id'] = $sid;
                $params['type'] = 3;
                $params['flow_id'] = $flow['flow_id'];
                $params['order_id'] = $flow['order_id'];
                $params['owner_staff_id']=$this->_staff->id;
                if ($flow['status'] == 0) {//发起人自选
                    if (empty($params['flow_staff_ids'])) {
                        $this->error('审批人必须选择');
                    }
                    $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
                } else {
                    if (empty($flow['flow_staff_ids'])) {
                        $this->error('没有直属上级无法审批，请联系管理员！');
                    }
                    $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
                }
                $data[] = $params;
            }
            $result = false;
            Db::startTrans();
            try {
                foreach ($data as $params){
                    $model        = new AchievementRecords();

                    if ($model->save($params) === false) {
                        throw new Exception('添加失败');
                    }
                    $lastId     = $model->getLastInsID();

                    if ($flow['status'] == 1) {//固定审批
                        //发送审批通知
                        Flow::sendStepRecord($flow,Flow::ACHIEVEMENT_STATUS, $lastId);
                    } else {//发起人自选 依次审批
                        $staff_id   = explode(',', $params['flow_staff_ids'])[0];
                        if ($staff_id) {
                            ExamineRecord::addExaminse(ExamineRecord::ACHIEVEMENT_TYPE, $lastId, $staff_id);
                        }
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('提交成功,等待审核中');
        }

        $flow=Flow::getsteplist(Flow::ACHIEVEMENT_STATUS);
        $this->assign('flow',$flow);
        $this->assign('department', StaffDepartment::getList());
        $staffs = Staff::where(['id'=>['in',Staff::getMyStaffIds()]])->where(["jigou_id"=>Session::get("jigou_id")])->field('id,name')->select();
        $this->assign('staffs', $staffs);
        $this->assign('years', getYears());
        return $this->view->fetch();
    }

    /**
     * 修改业绩目标
     * @param null $ids
     * @return string
     */
    public function edit($ids = null)
    {


        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $params = $this->preExcludeFields($params);
            Db::startTrans();
            try {

                $model        = new AchievementRecords();
                $flow = Flow::getsteplist(Flow::ACHIEVEMENT_STATUS);
                $params['flow_id'] = $flow['flow_id'];
                $params['order_id'] = $flow['order_id'];
                $params['owner_staff_id']=$this->_staff->id;
                if ($flow['status'] == 0) {//发起人自选
                    if (empty($params['flow_staff_ids'])) {
                        throw new Exception('审批人必须选择');
                    }
                    $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
                } else {
                    if (empty($flow['flow_staff_ids'])) {
                        throw new Exception('没有直属上级无法审批，请联系管理员！');
                    }
                    $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
                }
                if ($model->save($params) === false) {
                    throw new Exception('添加失败');
                }
                $lastId     = $model->getLastInsID();

                if ($flow['status'] == 1) {//固定审批
                    //发送审批通知
                    Flow::sendStepRecord($flow,Flow::ACHIEVEMENT_STATUS, $lastId);
                } else {//发起人自选 依次审批
                    $staff_id   = explode(',', $params['flow_staff_ids'])[0];
                    if ($staff_id) {
                        ExamineRecord::addExaminse(ExamineRecord::ACHIEVEMENT_TYPE, $lastId, $staff_id);
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('提交成功,等待审核中');
        }
        $row=AchievementModel::where(['id' => $ids])->with(['staff'])->find();
        $flow=Flow::getsteplist(Flow::ACHIEVEMENT_STATUS);

        $this->assign('flow',$flow);
        $this->assign('row', $row);

        return $this->view->fetch();
    }
    /**
     * 获取审批人列表
     */
    public function getstaff(){
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',$keyValue];
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $staff = Staff::where($where)->field('id,name')->order('id desc')->where("jigou_id", Session::get("jigou_id"))->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }
    /**
     * 团队目标
     * @param null $ids
     * @return string
     */
    public function edit_personal($ids = null)
    {

        $year = input('year');
        $status = input('status');
        if (empty($year) || empty($status)) {
            $this->error('参数错误');
        }
        if ($this->request->isAjax()) {

            $params = $this->request->post('row/a');
            $achievements = $this->preExcludeFields($params);
            $type         = 3;//员工
            $flow_staff_id = input('flow_staff_ids');

            $model        = new AchievementRecords();
            if (isset($achievements['yeartarget'])) {
                unset($achievements['yeartarget']);
            }
            $id = $this->_staff->id;
            $params = [
                'type'          => $type,
                'year'          => $year,
                'status'        => $status,
                'obj_id'        => $id,
                'january'       => $achievements['january'] ?? 0,
                'february'      => $achievements['february'] ?? 0,
                'march'         => $achievements['march'] ?? 0,
                'april'         => $achievements['april'] ?? 0,
                'june'          => $achievements['june'] ?? 0,
                'may'           => $achievements['may'] ?? 0,
                'july'          => $achievements['july'] ?? 0,
                'august'        => $achievements['august'] ?? 0,
                'september'     => $achievements['september'] ?? 0,
                'october'       => $achievements['october'] ?? 0,
                'november'      => $achievements['november'] ?? 0,
                'december'      => $achievements['december'] ?? 0,
                'flow_staff_ids' => $flow_staff_id,
                'owner_staff_id'=> $id,
                'check_status'  => 0,
                'yeartarget'    => array_sum(array_values($achievements)),
                'createtime'    => time(),
                'updatetime'    => time()
            ];
            Db::startTrans();
            try {
                if ($model->insert($params) == false) {
                    throw new Exception('添加失败');
                }
                $staff_id   = explode(',', $params['flow_staff_ids'])[0];
                $lastId     = $model->getLastInsID();
                if ($staff_id) {
                    ExamineRecord::addExaminse(ExamineRecord::ACHIEVEMENT_TYPE, $lastId, $staff_id);
                }
                Db::commit();;
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('提交目标成功，等待审核！');
        }

        $row = Staff::where(['id' => $ids])->with([
            "achievement" => function ($query) use ($year, $status) {
                $query->where(['year' => $year, 'status' => $status]);
            }
        ])->find();
        $this->assign('staff', Staff::getStaff());
        $this->assign('row', $row);
        $this->assign('year', $year);
        $this->assign('status', $status);

        return $this->view->fetch();
    }
    /**
     * 业绩目标详情
     * @param null $ids
     * @return string
     */
    public function detail($ids = null)
    {

        $row=AchievementRecords::where(['id' => $ids])->with(['staff'])->find();
        //标记通知已读
        Message::setRead(Message::ACHIEVEMENT_TYPE, $ids, $this->_staff->id);
        $this->assign('row', $row);

        return $this->view->fetch();
    }
}